'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview boss
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var async = require('async');
var modelUtil = require('../util/modelUtil');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var bossSchema = require('../schemas/bossSchema');
var Boss = mongoConnector().model('Boss');
var constantUtil = require('../util/constantUtil');

/**
 * 根据角色id获取掠夺数据
 */
module.exports.getByRoleId = function (role_id, cb) {
    function afterCreate(err, model) {
        cb(null, model);
    }

    function afterFindOne(err, schema) {
        if (!!err) {
            return cb(err);
        }
        if (!!schema) {
            return cb(null, schema);
        } else {
            Boss.create({
                role_id: role_id
            }, afterCreate);
        }
    }

    Boss.findOne({
        role_id: role_id
    }, afterFindOne);
};

/**
 * 5点刷新
 */
module.exports.onFiveRefresh = function (self, cb) {
    // 刷新剩余次数
    self.refresh();
    cb();
};

/**
 * 获取当前玩家伤害排名
 * @param  {Function} cb [description]
 * @return {[type]}      [description]
 */
module.exports.getRankByRoleId = function (role_id, max_damage, cb) {
    var count;
    var other_count;
    async.series(
        [
            function (cb) {
                Boss.where('max_damage')
                    .gt(max_damage)
                    .count(
                        function (err, num) {
                            count = num;
                            cb();
                        });
            },
            function (cb) {
                Boss.where('max_damage')
                    .equals(max_damage)
                    .where('role_id')
                    .lt(role_id)
                    .count(
                        function (err, num) {
                            other_count = num + 1;
                            cb();
                        });
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            cb(null, count + other_count);
        }
    );
};

/**
 * 获取玩家伤害排行榜
 */
module.exports.getTopRank = function (limit_cnt, cb) {
    Boss.find({
            max_damage: {
                $gt: 0
            }
        })
        .sort('-max_damage')
        .sort('-role_id')
        .limit(limit_cnt)
        .select('role_id max_damage select_soldier_list fight_power')
        .exec(cb);
};

/**
 * 删除所有数据
 * @param  {Function} cb [description]
 * @return {[type]}      [description]
 */
module.exports.removeAll = function (cb) {
    Boss.remove({}, cb);
};
